package org.sdp.pearproject.config;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.util.Date;

import org.sdp.pearproject.utils.DateUtil;
import org.springframework.util.StringUtils;

public class MyDatePropertyEditorSupport extends PropertyEditorSupport {

    @Override
    public void setValue(Object value) {
        super.setValue(value);
    }

    @Override
    public Object getValue() {
        return super.getValue();
    }

    @Override
    public void setAsText(String text) {
        if (!StringUtils.hasText(text)) {
            setValue(null);
            return;
        }
        try {
            int len = text.length();
            if (len == 19) {
                setValue(DateUtil.parseDatetime(text));
                return;
            }
            if (len == 10) {
                setValue(DateUtil.parseDate(text));
                return;
            }
        }catch(Exception ex) {
            ex.printStackTrace();
        }
        throw new java.lang.IllegalArgumentException("cannot set date by text:"+text);

    }

    @Override
    public String getAsText() {
        Object v = getValue();
        if (v == null) {
            return "";
        }
        return DateUtil.formatDatetime((Date) v);
    }
}